package
{
	import Events.SnakeChangeEvent;
	
	import Player.PlayerModel;
	import Player.SnakeHead;
	
	import Views.Field;
	import Views.SnakeView;
	
	import flash.events.KeyboardEvent;
	
	import mx.core.FlexGlobals;

	public class Game
	{
		private var players:Array = new Array();
		private var _field:Field;
		
		public function Game(field:Field)
		{			
			// Add snakeView to field
			_field = field;
			
			// Add keyboard listeners
			FlexGlobals.topLevelApplication.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			FlexGlobals.topLevelApplication.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			
			// Create player with a new snake
			var player:PlayerModel = new PlayerModel(createSnake());
			players.push(player);
		}
		
		public function onKeyDown(event:KeyboardEvent):void{
			// Update keystatus for all player
			for(var playerId:Number = 0; playerId < players.length; playerId++){
				var player:PlayerModel = players[playerId];
				
				// Update left and right key status
				if(player.isLeftKey(event.keyCode)){
					player.leftKeyStatus = true;
				}
				if(player.isRightKey(event.keyCode)){
					player.rightKeyStatus = true;
				}
			}
		}
		
		public function onKeyUp(event:KeyboardEvent):void{
			// Update keystatus for all player
			for(var playerId:Number = 0; playerId < players.length; playerId++){
				var player:PlayerModel = players[playerId];
				
				// Update left and right key status
				if(player.isLeftKey(event.keyCode)){
					player.leftKeyStatus = false;
				}
				if(player.isRightKey(event.keyCode)){
					player.rightKeyStatus = false;
				}
			}
		}
		
		public function createSnake(headColor:uint = 0xFF0000):SnakeHead{
			// Red snake for now
			var snake:SnakeHead = new SnakeHead(headColor);
			var snakeView:SnakeView = new SnakeView();
			
			// Add snake view to field
			_field.addSnake(snakeView);
			
			// Add view as listener to model
			snake.addEventListener(SnakeChangeEvent.HEAD_CHANGE,snakeView.updateSnakeHead);
			snake.addEventListener(SnakeChangeEvent.SNAKE_MOVE,snakeView.updateAfterMove);
			
			// Trigger first Snake head change event
			snake.setRoundHead();
			
			// Return new snake
			return snake;
		}
	}
}